package sg.edu.nus.iss.umpire.service.competition;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.datanucleus.util.StringUtils;

import sg.edu.nus.iss.umpire.domain.Competition;
import sg.edu.nus.iss.umpire.domain.CompetitionDay;
import sg.edu.nus.iss.umpire.exception.ServiceException;
import sg.edu.nus.iss.umpire.support.AppConstants;
import sg.edu.nus.iss.umpire.support.HttpMethod;
import sg.edu.nus.iss.umpire.support.Service;
import sg.edu.nus.iss.umpire.support.ServiceConfig;
import sg.edu.nus.iss.umpire.support.ServiceContext;

@ServiceConfig(path = "competitions/save", method = HttpMethod.POST)
public class SaveCompetitionService implements Service{

    @Override
    public String serve(ServiceContext ctx) throws Exception {
		Competition entity = null;

		String id = ctx.getRequest().getParameter("key");
		if (StringUtils.isEmpty(id)) {
			entity = new Competition();
		} else {
			Long key = Long.valueOf(id);
			entity = ctx.getEntityManager().find(Competition.class,
					Long.valueOf(key));
		}


		String name = ctx.getRequest().getParameter("name");
		Date startDate = parse(ctx.getRequest().getParameter("startDate"));
		Date endDate = parse(ctx.getRequest().getParameter("endDate"));
		String location = ctx.getRequest().getParameter("location");
		String refereeName = ctx.getRequest().getParameter("refereeName");
		Long refereeKey = Long.valueOf(trim(ctx.getRequest().getParameter(
				"refereeKey")));

		entity.setName(name);
		entity.setStartDate(startDate);
		entity.setEndDate(endDate);
		entity.setLocation(location);
		entity.setRefereeKey(refereeKey);
		entity.setRefereeName(refereeName);
		
		if (entity.getKey() == null){
			//only create competition day on creation
			//TODO fix the case when editing Competition
			createCompetitionDay(entity);
		}

		ctx.getEntityManager().merge(entity);
		return "redirect:/s/competitions";
    }

	private void createCompetitionDay(Competition competition) {
			Calendar c = Calendar.getInstance();
			c.setTime(competition.getStartDate());
			
			while(!c.getTime().after(competition.getEndDate())){
				//save competition day
				CompetitionDay day = new CompetitionDay();
//				day.setCompetitionKey(competition.getKey());
				day.setCompetitionName(competition.getName());
				day.setStartDate(competition.getStartDate());
				day.setEndDate(competition.getEndDate());
				day.setLocation(competition.getLocation());
				day.setRefereeName(competition.getRefereeName());
				day.setDate(format(c.getTime()));
				competition.getCompetitionDays().add(day);
				//increment
				c.add(Calendar.DAY_OF_MONTH, 1);
			}
	}
	
	private static Date parse(String dateStr) {
		SimpleDateFormat df = new SimpleDateFormat(AppConstants.DEFAULT_DATE_FORMAT);
		try {
			return df.parse(dateStr);
		} catch (ParseException e) {
			throw new ServiceException(String.format("Invalie date input: %s",
					dateStr));
		}
	}
	
	private static String format(Date date){
		SimpleDateFormat df = new SimpleDateFormat(AppConstants.DEFAULT_DATE_FORMAT);
		return df.format(date);
	}

	private String trim(String value) {
		if (StringUtils.isEmpty(value)) {
			return value;
		}

		return value.trim();
	}

}
